
package com.meteor.raft.persistent;

import com.meteor.raft.executor.GlobalExecutor;
import lombok.Data;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.atomic.AtomicLong;

/**
 * raft 节点信息
 */
@Data
public class RaftPeer {

    public String ip;

    public String voteFor;

    public AtomicLong term = new AtomicLong(0L);

    public volatile long leaderDueMs = RandomUtils.nextLong(GlobalExecutor.HEARTBEAT_INTERVAL_MS, GlobalExecutor.LEADER_TIMEOUT_MS);

    public volatile long heartbeatDueMs = GlobalExecutor.HEARTBEAT_INTERVAL_MS;

    public State state = State.FOLLOWER;

    public void resetLeaderDue() {
        leaderDueMs = GlobalExecutor.LEADER_TIMEOUT_MS + RandomUtils.nextLong(0, GlobalExecutor.RANDOM_MS);
    }


    public void resetHeartbeatDue() {
        heartbeatDueMs = GlobalExecutor.HEARTBEAT_INTERVAL_MS;
    }

    public enum State {
        /**
         * Leader of the cluster, only one leader stands in a cluster
         */
        LEADER,
        /**
         * Follower of the cluster, report to and copy from leader
         */
        FOLLOWER,
        /**
         * Candidate leader to be elected
         */
        CANDIDATE
    }
}
